from django import http
from django.conf import settings
from django.core import paginator

import core.url
from core import utils
from securities import models

def index(request):
  p = paginator.Paginator(models.Security.objects.all(), 20) 
  try:
    page = int(request.GET.get('page', '1'))
  except ValueError:
    page = 1
  
  return utils.render_to_response(
    'security/index.html',
    request,
    {'current_page': page,
     'paginator': p,
     'page_url': core.url.URL('/s/'),
     'securities': p.page(page).object_list}
  )

def summary_page(request, symbol):
  try:
    security = models.Security.getFromSymbol(symbol)
  except models.Security.SymbolInvalidError:
    return http.HttpResponseNotFound()
  
  return utils.render_to_response(
    'security/summary.html', 
    request,
    {'security': security}
  )
  
def initialize(request):
  # Ony allow admins to initialize
  if not request.user or request.user.fbid not in settings.ADMIN_FBIDS:
    return http.HttpResponse('Only admins are allowed to initialize')
  
  from core.initialization.security import initialize_securities
  initialize_securities()
  return http.HttpResponse('Initialization Complete')